package com.mida.dms.knw.service.impl;

import com.mida.dms.knw.mapper.DtOidMapper;
import com.mida.dms.knw.mapper.KnwConceptualDetailMapper;
import com.mida.dms.knw.mapper.KnwConceptualDomainMapper;
import com.mida.dms.knw.mapper.KnwConceptualMapper;
import com.mida.dms.knw.entity.DtOid;
import com.mida.dms.knw.entity.KnwConceptualDetail;
import com.mida.dms.knw.entity.vo.KnwConceptualDetailPage;
import com.mida.dms.knw.entity.vo.KnwConceptualDetailVo;
import com.mida.dms.knw.service.KnwConceptualDetailService;
import com.mida.dms.knw.service.SoidService;
import com.mida.dms.knw.util.DataSetConstants;
import com.mida.dms.knw.vo.KnwConceptualDetailPageVo;
import com.mida.dms.knw.vo.Page;
import com.mida.dms.knw.vo.PageResultVo;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.BaseResult;
import com.mida.tool.common.result.ListResult;
import com.mida.tool.common.utils.CharTransFormUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service
@Transactional
public class KnwConceptualDetailServiceImpl extends BaseResult implements KnwConceptualDetailService {

    @Autowired
    KnwConceptualDetailMapper knwConceptualDetailMapper;
    @Autowired
    private SoidService soidService;

//    /**
//     * ID生成器
//     */
//    @Autowired
//    private OIDGanerator oIDGanerator;
//    @Autowired
//    private KnwConceptualMapper knwConceptualMapper;

    @Autowired
    private KnwConceptualDomainMapper knwConceptualDomainMapper;
//    /**
//     * OID
//     */
//    @Autowired
//    private DtOidMapper dtOidMapper;

    public ActionResult add(KnwConceptualDetail t) {
        if (t.getConceptualDetailSoid() != null) {
            log.info(t.toString() + "不是一个新增，转到update去");
            return update(t);
        }
        log.info("开始新增一个概念描述" + t.toString());
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (StringUtils.isEmpty(t.getConceptualDetailName())) {
                throw new RuntimeException("名称不能为空");
            }

            int count = knwConceptualDetailMapper.countName(t.getConceptualDetailName());
            if (count > 0) {
                throw new RuntimeException("名称已存在");
            }
            int isPreferredConut = knwConceptualDetailMapper.countPreferred(t.getConceptualSoid());
            if (t.getIsPreferred() == 1L && isPreferredConut > 0) {
                throw new RuntimeException("首选标识只能有一个");
            }
            int  countTypeFsn= knwConceptualDetailMapper.countTypeFsn(t.getConceptualSoid(),DataSetConstants.FSN);
            if (DataSetConstants.FSN.equals(t.getConceptualDetailType()) &&  countTypeFsn>0) {
                throw new RuntimeException("概念描述类型FSN只能有一个");
            }
            t.setPyCode(CharTransFormUtil.toPinyinSimple(t.getConceptualDetailName()));
            t.setWbCode(CharTransFormUtil.toWubi(t.getConceptualDetailName()));
//            long seq = oIDGanerator.getSOID();
            long seq = soidService.getSoid();
            t.setConceptualDetailSoid(seq);
            t.setIsDelete(0L);
            knwConceptualDetailMapper.insert(t);
            soidService.insertOid(seq,1);
//            String soid = oIDGanerator.getOID(KNW_OID);
//
////            saveOid(seq, soid);
////            String oid = oIDGanerator.getOID(0);
//            DtOid dtOid = new DtOid();
//            dtOid.setOid(soid);
//            dtOid.setSoid(seq);
//            dtOidMapper.insert(dtOid);

            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("新增概念描述发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "新增概念描述发送异常");
        } finally {
            st.stop();
            log.info("本次新增耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    @Override
    public ActionResult update(KnwConceptualDetail t) {
        log.info("开始更新一个概念描述" + t.toString());
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (StringUtils.isEmpty(t.getConceptualDetailName())) {
                throw new RuntimeException("名称不能为空");
            }
            KnwConceptualDetail ns = knwConceptualDetailMapper.selectByPrimaryKey(t.getConceptualDetailSoid());
            if (ns == null) {
                throw new RuntimeException("概念描述不存在" + t.getConceptualDetailSoid());
            }
            int isPreferredConut = knwConceptualDetailMapper.countPreferred(t.getConceptualSoid());
            if (isPreferredConut > 0 && ns.getIsPreferred() != 1L && t.getIsPreferred() == 1L) {
                throw new RuntimeException("首选标识只能有一个");
            }
            if (!t.getConceptualDetailName().equals(ns.getConceptualDetailName())) {
                int count = knwConceptualDetailMapper.countName(t.getConceptualDetailName());
                if (count > 0) {
                    throw new RuntimeException("名称已存在");
                }
            }
            int  countTypeFsn= knwConceptualDetailMapper.countTypeFsn(t.getConceptualSoid(),DataSetConstants.FSN);
            if (DataSetConstants.FSN.equals(t.getConceptualDetailType()) &&  countTypeFsn>0 && ns.getConceptualDetailType()!=t.getConceptualDetailType()) {
                throw new RuntimeException("概念描述类型FSN只能有一个");
            }
            t.setPyCode(CharTransFormUtil.toPinyinSimple(t.getConceptualDetailName()));
            t.setWbCode(CharTransFormUtil.toWubi(t.getConceptualDetailName()));
            knwConceptualDetailMapper.updateByPrimaryKey(t);
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("更新概念描述发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "更新概念描述发送异常");
        } finally {
            st.stop();
            log.info("本次更新耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    @Override
    public ActionResult delete(long soid) {
        log.info("开始删除一个概念描述" + soid);
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            knwConceptualDetailMapper.deleteByPrimaryKey(soid);
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("删除概念描述发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "删除概念描述发送异常");
        } finally {
            st.stop();
            log.info("本次删除耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    @Override
    public ListResult<KnwConceptualDetail> get(long soid) {
        log.info("开始查询一个概念描述" + soid);
        StopWatch st = StopWatch.createStarted();
        ListResult<KnwConceptualDetail> lr = new ListResult<KnwConceptualDetail>();
        try {
            KnwConceptualDetail ns = knwConceptualDetailMapper.selectByPrimaryKey(soid);
            buildListSuccess(lr, ns);
        } catch (Exception e) {
            log.error("查概念描述发送异常", e);
            buildListWarn(lr, "查概念描述发送异常");
        } finally {
            st.stop();
            log.info("本次查询耗时:" + st.getTime() + "ms");
        }
        return lr;
    }

    @Override
    public ListResult<PageResultVo<KnwConceptualDetailVo>> findPage(KnwConceptualDetailPageVo vo) {
        log.info("开始分页查询,查询条件:" + vo.toString());
        PageResultVo pvo = new PageResultVo();
        Page page = new Page(vo.getCurrentPage(), vo.getPageSize());
        pvo.setPage(page);
        StopWatch st = StopWatch.createStarted();
        ListResult result = new ListResult();
        List<KnwConceptualDetailVo> list = null;
        try {
            KnwConceptualDetailPage npage = new KnwConceptualDetailPage(vo.getCurrentPage(), vo.getPageSize(), vo.getSearChData(), vo.getConceptualSoid());
            int count = knwConceptualDetailMapper.findPageCount(npage);
            if (count != 0) {
                page.setTotalCount(count);
                list = knwConceptualDetailMapper.findPageByDetail(npage);
            } else {
                pvo.setPage(null);
            }
            pvo.setList(list);
            buildListSuccess(result, pvo);
        } catch (Exception e) {
            list = new ArrayList<KnwConceptualDetailVo>(0);
            pvo.setList(list);
            log.error("分页查概念描述发送异常", e);
            buildListWarn(result, "分页查概念描述发送异常");
        } finally {
            st.stop();
            log.info("本次分页查询耗时:" + st.getTime() + "ms");
        }
        return result;
    }

    @Override
    public ActionResult checkName(Long soid, String name) {
        log.info("开始检查是否重名" + name);
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            if (soid != null) {
                KnwConceptualDetail ns = knwConceptualDetailMapper.selectByPrimaryKey(soid);
                if (ns == null) {
                    throw new RuntimeException("概念描述不存在" + name);
                }
                if (name.equals(ns.getConceptualDetailName())) {
                    //与原始名称一致，不处理
                    buildActionSuccess(ar);
                    return ar;
                }
            }
            int count = knwConceptualDetailMapper.countName(name);
            if (count > 0) {
                throw new RuntimeException("名称已存在");
            }
            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("检查概念描述发送异常", e);
            buildActionWarn(ar, "检查概念描述发送异常");
        } finally {
            st.stop();
            log.info("本次检查耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

    @Override
    public ActionResult setFirst(Long soid, Long conceptualSoid, Long isConceptualDomain) {
        log.info("开始设置概念描述首选" + soid);
        StopWatch st = StopWatch.createStarted();
        ActionResult ar = new ActionResult();
        try {
            KnwConceptualDetail ns = knwConceptualDetailMapper.selectByPrimaryKey(soid);
            knwConceptualDetailMapper.updateKnwConceptualDetailAll(ns.getConceptualSoid());
            ns.setIsPreferred(1L);
            knwConceptualDetailMapper.updateByPrimaryKey(ns);

            buildActionSuccess(ar);
        } catch (Exception e) {
            log.error("设置概念描述首选发送异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            buildActionWarn(ar, "设置概念描述首选发送异常");
        } finally {
            st.stop();
            log.info("本次设置耗时:" + st.getTime() + "ms");
        }
        return ar;
    }

}
